<template>
    <div class="menu-view" id="menu-scroll-view">
        <div class="body">
            <div
                class="category-item"
                v-for="(categoryItems, categoryIndex) in menuList"
                :key="categoryIndex"
                :id="categoryItems.categoryId"
            >
                <div class="category-name">
                    {{ categoryItems.categoryName }}
                </div>
                <div
                    class="product-item"
                    v-for="(item, index) in categoryItems.list"
                    :key="index"
                >
                    <MenuItem
                        :categoryId="categoryItems.categoryId"
                        :categoryName="categoryItems.categoryName"
                        :item="item"
                    />
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import MenuItem from "./menuItem";
import mockData from "./mock";
import { throttle } from "@/utils/tools";
export default {
    components: {
        MenuItem
    },
    props: {
        menuList: {
            type: Array,
            default() {
                return mockData;
            }
        }
    },
    data() {
        return {
            elemList: []
        };
    },
    mounted() {
        let elemList = this.menuList.map(i => {
            const id = i.categoryId;
            return document.getElementById(id);
        });
        this.elemList = elemList;
        this.baseline = elemList[0].getBoundingClientRect().top;

        this.bindScroll();
        console.log("baseline", elemList[0].getBoundingClientRect().top);
    },

    methods: {
        bindScroll() {
            const scrollView = document.getElementById("menu-scroll-view");
            scrollView.addEventListener("scroll", this.onScroll);
            this.$emit("change", {
                id: this.elemList[0].id
            });
        },
        onScroll: throttle(function() {
            let current = this.elemList[0].id;

            this.elemList.forEach(elem => {
                let top = elem.getBoundingClientRect().top - this.baseline;
                if (top < 0) {
                    current = elem.id;
                }
            });
            // console.log(current);

            this.$emit("change", {
                id: current
            });
        })
    }
};
</script>


<style lang="less" scoped>
.menu-view {
    flex: 1 1 auto;
    box-sizing: border-box;
    overflow-y: scroll;

    .body {
        position: relative;
        width: 100%;
        // height: 100%;
        .category-item {
            background: #f4f4f4;
            padding-bottom: 30px;
            .category-name {
                padding: 20px 0 20px 30px;
                font-size: 26px;
                background: #fff;
            }

            .product-item {
                background: #fff;
            }
        }
    }
}
</style>